<template>
  <view class="uni-container">

    <uni-popup ref="message" type="message">
				<uni-popup-message type="error" :message="messageText" :duration="1500"></uni-popup-message>
		</uni-popup>

    <uni-forms ref="form" :model="formData" validateTrigger="bind">
      <uni-forms-item name="school_id" label="所属学校" required>
        <uni-data-picker v-model="formData.school_id" collection="admin-school-list" field="school_name as text, _id as value"></uni-data-picker>
      </uni-forms-item>
      <uni-forms-item name="send_date" label="送达日期" required>
        <uni-easyinput placeholder="左侧预计送达日期，$now 表示今天，$now1 表示明天" v-model="formData.send_date" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="start_time" label="起送时间" required>
        <uni-datetime-picker :start="formData.name" return-type="timestamp" v-model="formData.start_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="end_time" label="结束时间" required>
        <uni-datetime-picker :start="formData.start_time" :end="`${formData.name} 23:00:00`" :disabled="formData.name.trim()===''" return-type="timestamp" v-model="formData.end_time"></uni-datetime-picker>
      </uni-forms-item>
      <uni-forms-item name="name" label="菜单名称" required>
        <uni-easyinput :disabled="true" placeholder="预计送达左侧菜单名称" v-model="formData.name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="alias_name" label="菜单别名">
        <uni-easyinput placeholder="预计送达左侧菜单名称别名，例如：今天、明天、后天" v-model="formData.alias_name" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="alias_first_time" label="时间别名" v-if="formData.send_date==='$now'">
        <uni-easyinput placeholder="右侧预计起送时间第一位显示名称，例如：两小时内送达" v-model="formData.alias_first_time" trim="both"></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item name="splice_mode" label="时间间隔">
        <uni-data-checkbox v-model="formData.splice_mode" :localdata="formOptions.splice_mode_localdata"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="enable" label="启用或关闭">
        <switch style="transform: scale(0.8);" @change="binddata('enable', $event.detail.value)" :checked="formData.enable"></switch>
      </uni-forms-item>
      <uni-forms-item name="splice_time" label="右侧菜单" required>
        <uni-data-checkbox mode="button" :localdata="formData.splice_time_text" :multiple="true" v-model="formData.splice_time"></uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="splice_time_text" label="菜单内容" required style="display:none">
        <uni-data-checkbox :multiple="true" v-model="formData.splice_time_text"></uni-data-checkbox>
      </uni-forms-item>
      <view class="uni-button-group">
        <button type="primary" class="uni-button" style="width: 100px;" @click="submit">提交</button>
        <navigator open-type="navigateBack" style="margin-left: 15px;">
          <button class="uni-button" style="width: 100px;">返回</button>
        </navigator>
      </view>
    </uni-forms>
  </view>
</template>

<script>
  import moment from "moment";
  import { validator } from '../../js_sdk/validator/admin-send-time.js';

  const db = uniCloud.database();
  const dbCmd = db.command;
  const dbCollectionName = 'admin-send-time';

  function getValidator(fields) {
    let result = {}
    for (let key in validator) {
      if (fields.includes(key)) {
        result[key] = validator[key]
      }
    }
    return result
  }

  

  export default {
    data() {
      let formData = {
        "school_id": "",
        "send_date": "",
        "start_time": null,
        "end_time": null,
        "name": "",
        "alias_name": "",
        "alias_first_time": "一小时内送达",
        "splice_mode": 0,
        "enable": true,
        "splice_time": [],
        "splice_time_text": []
      }
      return {
        formData,
        formOptions: {
          "splice_mode_localdata": [
            {
              "value": 0,
              "text": "一小时"
            },
            {
              "value": 1,
              "text": "两小时"
            },
            {
              "value": 2,
              "text": "三小时"
            }
          ]
        },
        rules: {
          ...getValidator(Object.keys(formData))
        },
        messageText:``
        }
    },
    watch:{
      'formData.start_time'(val){
        this.spliceTimeCreate();
      },
      'formData.end_time'(val){
        this.spliceTimeCreate();
      },
      'formData.splice_mode'(val){
        const modeToggle={
            0:`一小时内送达`,
            1:`两小时内送达`,
            2:`三小时内送达`
      }
        this.formData.alias_first_time=modeToggle[val];
        this.spliceTimeCreate();

    },
      'formData.send_date'(val){
        const value=val.trim();
        const array=value.match(/^\$now([1-9]\d*)*$/)
        if(array==null){
          this.messageText=`时间格式不正确，请输入正确的时间格式`;
          return this.$refs.message.open()
      }
        const showAliasName={
          'undefined':`今天`,
          1:`明天`,
          2:`后天`
        }

        const nowTime=moment(new Date());
        this.formData.name=nowTime.format(`YYYY-MM-DD`);
        const [today,after]=array;
        let aliasName=showAliasName[after]

        if(after!=null){
          const afterName=nowTime.set('hour', after*24).format(`YYYY-MM-DD`);
          if(aliasName==null){
            aliasName=afterName;
          }
          this.formData.name=afterName
        }

        this.formData.alias_name=aliasName

        this.formData.start_time=moment(`${this.formData.name} 09:00:00`).valueOf();
        this.formData.end_time=moment(`${this.formData.name} 21:00:00`).valueOf();

      }
    },
    onReady() {
      this.$refs.form.setRules(this.rules)
    },
    methods: {
      
      spliceTimeCreate(){
        const end_time=this.formData.end_time;
        const start_time=this.formData.start_time;
        if(end_time==null||start_time==null){
          return false
        }
        const startH=moment(start_time).get(`hour`);
        const endH=moment(end_time).get(`hour`);
        const splice_mode=this.formData.splice_mode
        const diffH=endH-startH;

        if(diffH<(splice_mode+1)){
          const tips=this.formOptions.splice_mode_localdata[splice_mode].text
          this.messageText=`开始时间和结束时间必须大于${tips}`;
          return this.$refs.message.open()
        }

        const splice_time_text=[];

        const spliceMode=splice_mode+1

        for(let i=0,min=start_time;i<(Math.floor(diffH/(spliceMode)));i++){
          const max=min + spliceMode*1000*60*60*1;
          const startText = moment( min ).format(`HH:mm`)
          const endText = moment( max).format(`HH:mm`);

          splice_time_text.push({
            value:i,
            disable:true,
            max,min, text:`${startText} - ${endText}`
          })

          min=max;

        }

        this.formData.splice_time_text=splice_time_text;
        this.formData.splice_time=splice_time_text.map(it=>it.value)

      },

      /**
       * 验证表单并提交
       */
      submit() {
        uni.showLoading({
          mask: true
        })
        this.$refs.form.validate().then((res) => {
          return this.submitForm(res)
        }).catch(() => {
        }).finally(() => {
          uni.hideLoading()
        })
      },

      /**
       * 提交表单
       */
      submitForm(value) {
        // 使用 clientDB 提交数据
        return db.collection(dbCollectionName).add(value).then((res) => {
          uni.showToast({
            title: '新增成功'
          })
          this.getOpenerEventChannel().emit('refreshData')
          setTimeout(() => uni.navigateBack(), 500)
        }).catch((err) => {
          uni.showModal({
            content: err.message || '请求服务失败',
            showCancel: false
          })
        })
      }
    }
  }
</script>
